﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;

namespace ModelBinder.Host.Infrastructures.ModelBinders;

public class CustomBodyWrapModelBinder : IModelBinder
{
    private readonly BodyModelBinder _bodyModelBinder;
    private readonly CustomJsonValueModelBinder _customBodyModelBinder;

    public CustomBodyWrapModelBinder(BodyModelBinder bodyModelBinder, CustomJsonValueModelBinder customBodyModelBinder)
    {
        _bodyModelBinder = bodyModelBinder;
        _customBodyModelBinder = customBodyModelBinder;
    }

    public async Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext.BindingSource.CanAcceptDataFrom(FromCustomJsonValueAttribute.CustomJsonValue))
        {
            await _customBodyModelBinder.BindModelAsync(bindingContext);
            return;
        }

        if (_customBodyModelBinder != null)
        {
            await _customBodyModelBinder.BindModelAsync(bindingContext);
        }

        if (_bodyModelBinder != null && !bindingContext.Result.IsModelSet)
        {
            await _bodyModelBinder.BindModelAsync(bindingContext);
        }
    }
}